import React, { useEffect, useState, useRef } from "react";

import styled from "styled-components";
import eventBus from "@/utils/eventBus";

import { useNavigate } from "react-router-dom";

import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";

import { Water } from "three/examples/jsm/objects/Water.js";

// 组件-------------------------------------------------------------------------
const Title = styled.div``;

const Panel = styled.div`
  position: absolute;
  width: 80%;
  height: 80%;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
`;

const Group = styled.div`
  min-height: 200px;
  width: 100%;
  margin: 10px;
`;

const Item = styled.div`
  width: 300px;
  height: 190px;
`;

const Image = styled.div`
  background-size: 100% 100%;
  width: 200px;
  height: 140px;
`;

// 数据-------------------------------------------------------------------------

const threeGroup = [{ title: "模型绘制", image: "", url: "" }];

const toolGroup = [{ title: "颜色值编辑器", image: "", url: "" }];

function Home() {
  let lastRaf = -1;
  const mountRef = useRef<HTMLDivElement>(null!);
  const navigate = useNavigate();

  useEffect(() => {
    // 创建场景、相机和渲染器
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(
      70,
      window.innerWidth / window.innerHeight,
      0.1,
      1800
    );
    camera.position.set(-6.25, 1.52, -0.63);
    camera.position.y = Math.max(camera.position.y, 0);

    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);

    // 增加环境光源
    const light = new THREE.AmbientLight();
    scene.add(light);
    const mountNode = mountRef.current;

    mountNode.appendChild(renderer.domElement);

    // 创建控制器
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true; // 启用阻尼感
    controls.maxPolarAngle = THREE.MathUtils.degToRad(90);

    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("/assets/three/lib/draco/"); // 设置DRACO解码器的路径
    const loader = new GLTFLoader().setDRACOLoader(dracoLoader);

    // glb天空盒
    loader.load(
      "/models/forest.glb",
      function (gltf) {
        gltf.scene.scale.set(3, 3, 3);
        scene.add(gltf.scene);
      },
      undefined,
      function (error) {
        console.error(error);
      }
    );

    const texture = new THREE.TextureLoader().load("textures/alarm.png");

    let material = new THREE.SpriteMaterial({
      map: texture,
      color: "#ff0000",
      transparent: true,
      opacity: 1,
      depthWrite: false,
    });
    const sprite = new THREE.Sprite(material);

    scene.add(sprite);
    setInterval(() => {
      const number = Math.floor(Math.random() * 10);
      sprite.material.color.set(`#ff${number}ff${number}`);
    }, 2000);
    let circle_n = 0;
    function animate() {
      // 更新摄像机世界矩阵和逆世界矩阵
      lastRaf = requestAnimationFrame(animate);
      camera.updateMatrixWorld();
      circle_n = circle_n > 2 ? 0 : circle_n + 0.018;
      sprite.scale.set(
        0.5 * circle_n + 0.5,
        0.5 * circle_n + 0.5,
        0.5 * circle_n + 0.5
      );
      if (sprite.material) {
        sprite.material.opacity =
          circle_n === 0 ? 1 : sprite.material.opacity - 0.009;
      }
      camera.position.y = Math.max(camera.position.y, 0);
      controls.update();
      renderer.render(scene, camera);
      // console.log("三角面数", renderer.info.render.triangles);
    }

    function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    }

    window.addEventListener("resize", onWindowResize);

    animate();

    return () => {
      cancelAnimationFrame(lastRaf); // 清理渲染动画
      window.removeEventListener("resize", onWindowResize);
      renderer.dispose();
    };
  }, []);

  const handleNavigation = (path: string) => {
    navigate(path);
  };

  return (
    <div>
      <div ref={mountRef}></div>
      <Panel>
        <Group>
          <Item>
            <Title>图片</Title>
            <Image className="bg-[url('image/3dMap.png')] h-48"></Image>
          </Item>
        </Group>
        <Group></Group>
        <Group></Group>
      </Panel>
    </div>
  );
}

export default Home;
